package servlet;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import swimv2.session.IAbilityManagerRemote;
import utils.SCmd;

/**
 * Servlet implementation class Ability
 */
public class Ability extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Ability() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processrequest(request,response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processrequest(request,response);
	}

	private void processrequest(HttpServletRequest request, HttpServletResponse response)  throws IOException {
		HttpSession session = request.getSession();
		
		String s = request.getParameter(SCmd.SERVLET_COMMAND);
		
		if(s.equals(SCmd.ABILITY_CREATE))
		{
			String nome = request.getParameter("nome");
			String id = request.getParameter("utente");
			if(id.isEmpty()){ aggiungi(nome,request, response);}
			else elimina(nome, Integer.getInteger(id),request,response);
			
		}
		
	}

	
	private void elimina(String ab, Integer u, HttpServletRequest request,  HttpServletResponse response) throws IOException{
		InitialContext ctx;
		try {
			
			ctx = new InitialContext();
			IAbilityManagerRemote a = (IAbilityManagerRemote) ctx.lookup("IAbilityManagerRemote");
			a.removeAbility(ab, u);
			response.sendRedirect(response.encodeRedirectURL( "home_admin.jsp"));
			
		} catch (NamingException e) {
			
			e.printStackTrace();
		}
		
			
	}
	private void aggiungi ( String ab, HttpServletRequest request,  HttpServletResponse response) throws IOException{
		InitialContext ctx;
		try {
			
			ctx = new InitialContext();
			IAbilityManagerRemote a = (IAbilityManagerRemote) ctx.lookup("IAbilityManagerRemote");
			a.createAbility(ab);
			response.sendRedirect(response.encodeRedirectURL( "home_admin.jsp"));
			
		} catch (NamingException e) {
			
			e.printStackTrace();
		}
		
			
	}

}
